﻿using System;
using System.Collections.Generic;
using BotonJXC.Entity;
using WarehouseProductDAO = BotonJXC.DAO.WarehouseProductDAO;
using BotonJXC.Util;
using NHibernate.Criterion;

namespace BotonJXC.BLL
{
    public class WarehouseProductBLL : BaseBLL<WarehouseProductDAO, WarehouseProduct, int>
    {
        public WarehouseProductBLL()
        {
        }

        public WarehouseProduct Get(int warehouseId, int productId, int supplierId)
        {
            List<ICriterion> criterions = new List<ICriterion>();
            criterions.Add(Restrictions.Eq("Warehouse.WarehouseId", warehouseId));
            criterions.Add(Restrictions.Eq("Product.ProductId", productId));
            criterions.Add(Restrictions.Eq("Supplier.SupplierId", supplierId));
            return Dao.FindUnique(criterions.ToArray());
        }
        /// <summary>
        /// 增加或减少库存
        /// </summary>
        /// <param name="warehouseId">仓库地ID</param>
        /// <param name="productId">货ID</param>
        /// <param name="supplierId">供应商ID</param>
        /// <param name="quantity">数量 负数为减少 正数为增加</param>
        public void OptQuantity(int warehouseId, int productId, int supplierId, double quantity)
        {
            if (quantity != 0)
            {
                WarehouseProduct wp = Get(warehouseId, productId, supplierId);
                if (wp == null)
                {
                    wp = new WarehouseProduct();
                    wp.Product = new Product();
                    wp.Product.ProductId = productId;
                    wp.Supplier = new Supplier();
                    wp.Supplier.SupplierId = supplierId;
                    wp.Warehouse = new Warehouse();
                    wp.Warehouse.WarehouseId = warehouseId;
					wp.Quantity = quantity;
					Save(wp);
                }
				else
				{
					wp.Quantity += quantity;
					Update(wp);
				}
            }
        }

        /// <summary>
        /// 增加或减少库存
        /// </summary>
        /// <param name="warehouseId">仓库地ID</param>
        /// <param name="productId">货ID</param>
        /// <param name="quantity">数量 负数为减少 正数为增加</param>
        public void OptQuantity(int warehouseId, int productId, double quantity)
        {
            OptQuantity(warehouseId, productId, 0, quantity);
        }
    }
}